// user 模块相关
import { login, register, getUserInfoAPI, changeUserInfoAPI, changeAvatarAPI } from '@/api/user'
import { getToken, setToken, delToken, getuserInfo, setuserInfo } from '@/utils/storage'
export default {
  namespaced: true,
  state () {
    return {
      token: getToken(),
      userInfo: getuserInfo()
    }
  },
  mutations: {
    setUserToken (state, newToken) {
      state.token = newToken
      setToken(newToken)
    },
    delUserToken (state) {
      state.token = ''
      state.userInfo = {}
      delToken()
    },
    // 初始化用户信息
    initUserInfo (state, info) {
      state.userInfo = info
      setuserInfo(state.userInfo)
    }
    // 修改用户信息
  },
  computed: {
  },
  actions: {
    // 登录
    async loginAction (context, obj) {
      // 发送登录请求
      const res = await login(obj)
      context.commit('setUserToken', res.token)
    },
    // 注册
    async registerAction (context, obj) {
      // 发送注册请求
      const res = await register(obj)
      return res
    },
    // 退出登录
    async quitAction (context) {
      context.commit('delUserToken')
    },
    // 初始化用户基本信息
    async getUserInfoAction (context) {
      const res = await getUserInfoAPI()
      context.commit('initUserInfo', res.data)
    },
    // 修改用户基本信息
    async changeUserInfoAction (context, obj) {
      await changeUserInfoAPI(obj)
      await context.dispatch('getUserInfoAction')
    },
    // 修改用户头像
    async changeUserAvatarAction (context, obj) {
      await changeAvatarAPI(obj)
      await context.dispatch('getUserInfoAction')
    }
  },
  getters: {
  }
}
